﻿using IpPortDemo.Tools;
using Newtonsoft.Json;

namespace IpPortDemo.Filter
{
    /// <summary>
    /// IP地址、端口中间件
    /// </summary>
    public class IpPortMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly IConfiguration _configuration;


        public IpPortMiddleware(RequestDelegate next, IConfiguration configuration)
        {
            _next = next;
            _configuration = configuration;
        }


        public async Task InvokeAsync(HttpContext context)
        {
            //获取服务器外网ip
            string wanIp = NetHelper.GetWanIp();

            //获取局域网ip
            string ipLocation = NetHelper.GetLanIp();

            //获取端口
            var port = context.Connection.LocalPort.ToString();

            //获取域名 + 端口
            var host = context.Request.Host.Value; // 获取域名 + 端口

            //组合信息
            var msg = $"外网ip:{wanIp},局域网Ip:{ipLocation},端口:{port},主机:{host}";

            //获取当前时间
            var now = DateTime.Now;

            //检查客户端的 IP 地址是否在授权列表中，此处我们用配置文件换下，实际项目是需要从数据库中获取的
            var list = GlobalContext.AllowedIpPort.Url;

            var result = false;

            if (list.Contains(wanIp + ":" + port))
            {
                result= true;
            }

            //如果客户端的 IP 地址不在列表中，返回 403 Forbidden 错误

            //by---jck
            //设置 CORS 头 普通的ajax请求只需要设置Access-Control-Allow-Origin即可，如果是vue还需要配置Access-Control-Allow-Methods，Access-Control-Allow-Headers
            context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            context.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            context.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization");

            context.Response.ContentType = "application/json";
            context.Response.StatusCode = StatusCodes.Status200OK;

            //检查客户端的 IP 地址是否在授权列表中,后续tag改为403
            if (!result)
            {
                var payload = JsonConvert.SerializeObject(new { total = 0, data = "", tag = 0, message = $"ip和端口并未授权！", description = msg });
                await context.Response.WriteAsync(payload);
                return;
            }
            else
            {
                //检查授权时间,后续的更多操作可以根据需求添加，比如授权时间
               
            }

            await _next(context);
        }
    }
}
